package com.cardbaobao.cardbabyclient.model.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.cardbaobao.cardbabyclient.model.database.CbbDataBase;
import com.cardbaobao.cardbabyclient.model.database.SQL;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jiangzx on 2017/7/11 10:21.
 * 红包申请记录
 */

public class RedEnvelopesRecordDao {
    /**提交红包申请记录到服务器时的间隔时间*/
    public static final long RECORD_COMMIT_INTERVAL=30*60*1000L;

    private static final String TABLE_NAME= SQL.TABLE_RED_ENVELOPES_RECORD;
    private static final String KEY_ID_S="id";
    private static final String KEY_TIME_L="time";

    private SQLiteDatabase mDataBase;

    public static class RedEnvelopesRecord{
        public String id;//红包id
        public long time;//点击红包时的时间
        public RedEnvelopesRecord(String id,long time){
            this.id=id;
            this.time=time;
        }
    }

    public RedEnvelopesRecordDao(){
        init();
    }

    private synchronized SQLiteDatabase init(){
        CbbDataBase dataBaseHelper=
                new CbbDataBase(ApplicationHelper.getApplicationContext(),
                        SQL.DB_NAME,null,SQL.DB_VERSION);
        if(mDataBase==null||!mDataBase.isOpen()){
            mDataBase=dataBaseHelper.getWritableDatabase();
        }
        return mDataBase;
    }

    private void closeDateBase(){
        if(null!=mDataBase){
            mDataBase.close();
            mDataBase=null;
        }
    }

    /**获取所有红包记录[按时间升序排序]*/
    public List<RedEnvelopesRecord> getAllRedEnvelopesRecordAsc(){
        init();
        List<RedEnvelopesRecord> list = new ArrayList<>();
        Cursor cursor=mDataBase.query(TABLE_NAME,new String[]{KEY_ID_S,KEY_TIME_L},null,null,null,null,KEY_TIME_L+" asc");
        if(cursor!=null){
            if(cursor.moveToFirst()){
                for(int i=0,size=cursor.getCount();i<size;i++){
                    list.add(new RedEnvelopesRecord(
                            cursor.getString(cursor.getColumnIndex(KEY_ID_S)),
                                    cursor.getLong(cursor.getColumnIndex(KEY_TIME_L))));
                }

            }
            cursor.close();
        }
        closeDateBase();
        return list;
    }

    /**
     * 插入所有红包申请记录
     * @param record 红包申请记录
     */
    public void insertRedEnvelopesRecords(RedEnvelopesRecord record){
        if(record!=null){
            init();
            ContentValues values=new ContentValues(2);
            values.put(KEY_ID_S,record.id);
            values.put(KEY_TIME_L,record.time);
            mDataBase.insert(TABLE_NAME,null,values);
            closeDateBase();
        }
    }

    /**
     * 清除红包记录
     */
    public void clearRedEnvelopesRecords(){
        init();
        mDataBase.delete(TABLE_NAME,null,null);
        closeDateBase();
    }
}
